package com.open4cn.simulator.parser.datacolor.dc600;

import com.open4cn.simulator.answer.LogInstructionAction;
import com.open4cn.simulator.answer.datacolor.RemoveSlotAction;
import com.open4cn.simulator.answer.datacolor.RemoveSlotAnswer;
import com.open4cn.simulator.core.answer.AbstractAnswer;
import com.open4cn.simulator.core.answer.AnswerResponse;
import com.open4cn.simulator.core.ext.DataColorStatus;
import com.open4cn.simulator.core.parser.IInstructionParser;
import com.open4cn.simulator.core.parser.InstructionParserChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description *R0  00C2:
 * *R1  00C3:
 * *R2  00C4:
 * *R3  00C5:
 * *R4  00C6:
 * *R5  00C7:
 * *R6  00C8:
 * *R7  00C9:
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-03 17:41
 */
public class R$00C$Pattern implements IInstructionParser {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String COMMAND = "*R$  00C$";

    private RemoveSlotAnswer answer = new RemoveSlotAnswer();

    private DataColorStatus dataColorStatus;

    public R$00C$Pattern(DataColorStatus dataColorStatus) {
        this.dataColorStatus = dataColorStatus;
        init();
    }

    private void init() {
        answer.setActions(Arrays.asList(
                new LogInstructionAction(),
                new RemoveSlotAction()
        ));
    }

    @Override
    public Object parse(Object msg, InstructionParserChain chain) {
        String instruction = (String) msg;
        if (!match(instruction)) {
            return chain.filter(msg);
        }
        Integer slot = slot(instruction);
        AnswerResponse response = this.answer.answer(dataColorStatus, slot, instruction);
        return response.getData();
    }

    @Override
    public List<AbstractAnswer> getAnswers() {
        return Arrays.asList(answer);
    }

    /**
     * 匹配
     *
     * @param instruction
     * @return
     */
    private boolean match(String instruction) {
        if (null == instruction) {
            return false;
        }

        if (COMMAND.length() != instruction.length()) {
            return false;
        }

        for (int i = 0, len = COMMAND.length(); i < len; i++) {
            String charAt = String.valueOf(COMMAND.charAt(i));
            if ("$".equals(charAt)) {
                continue;
            }
            if (COMMAND.charAt(i) != instruction.charAt(i)) {
                return false;
            }
        }
        return true;
    }

    private Integer slot(String instruction) {
        String slot = instruction.substring(2, 3);
        return Integer.valueOf(slot);
    }
}
